package com.lineng.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lineng.dao.GeneralizeMapper;
import com.lineng.pojo.Generalize;
import com.lineng.service.GeneralizeService;
import com.lineng.util.FileUtils;
import com.lineng.util.VerificationUtil;

@Service
public class GeneralizeServiceImpl implements GeneralizeService {

	@Autowired
	GeneralizeMapper generalizeMapper;

	@Autowired
	private HttpServletRequest request;

	public List<Generalize> getGeneralize() {

		List<Generalize> generalizes = null;
		generalizes = generalizeMapper.selectByExampleWithBLOBs(null);
		if (VerificationUtil.verification(request) == 0) {
			for (int i = 0; i < generalizes.size(); i++) {

				if (generalizes.get(i).getReader() != null && generalizes.get(i).getReader() != 0) {
					int result = generalizes.get(i).getReader() + 1;
					generalizeMapper.updateGeneralizeReader(result);
				} else {
					generalizeMapper.updateGeneralizeReader(1);
				}
			}
		}
		return generalizes;
	}

	public int updateGeneraliza(Generalize generalize, MultipartFile file, String username) {
		if (VerificationUtil.verification(request) == 1) {
			int num = 0;
			// 获得项目的路径
			ServletContext sc = request.getSession().getServletContext();
			// 上传位置
			String path = sc.getRealPath("/") + generalize.getPath(); // 设定文件保存的目录
			if (file != null) {
				try {
					FileUtils.saveFile(file, path, 997, 729);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (generalize != null) {
				generalize.setPeople(username);
				generalize.setDate(new Date());
				num = generalizeMapper.updateByPrimaryKeySelective(generalize);
			}
			return num;
		}
		return 0;
	}

}
